<?php

class Xzsdsplus_Costpriceplus_IndexController extends Mage_Adminhtml_Controller_Action {
    
    protected function _construct() {
        $this->setUsedModuleName('Xzsdsplus_Costpriceplus');
    }
    
    protected function _initBanner($getRootInstead = false) {
        
        $this->_title($this->__('Catalog'))->_title($this->__('Manage Banner'));

        $banner_id = (int) $this->getRequest()->getParam('id', false);
        $storeId = (int) $this->getRequest()->getParam('store');
        $banner = Mage::getModel('costpriceplus/banner');
        $banner->setStoreId($storeId);

        if ($banner_id) {
            $banner->load($banner_id);
        }

        Mage::register('costpriceplus', $banner);
        return $banner;
    }
    
    public function indexAction() {
        
        $this->_initBanner();
        $this->loadLayout();
        $this->_setActiveMenu('catalog/costpriceplus');
        $this->renderLayout();
    
    }
    
    public function newAction() {
        
        $this->_initBanner();
        
        if ($this->getRequest()->getQuery('ajax')) {
            $this->_forward('grid');
            return;
        }

        $this->loadLayout();
        $this->_setActiveMenu('catalog/costpriceplus');
        $this->_addContent($this->getLayout()->createBlock('costpriceplus/edit'))
                ->_addLeft($this->getLayout()->createBlock('costpriceplus/tabs'));
        $this->renderLayout();
        
    }
    
    public function editAction() {
        
        $id     = $this->getRequest()->getParam('id');
        $model  = $this->_initBanner();

        if ($model->getId() || $id == 0) {
            $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
            if (!empty($data)) {
                $model->setData($data);
            }
            //var_dump($model->getBanner_id());
            //Mage::register();
            $this->loadLayout();
            $this->_setActiveMenu('catalog/costpriceplus');

            $this->_addContent($this->getLayout()->createBlock('costpriceplus/edit'))
                ->_addLeft($this->getLayout()->createBlock('costpriceplus/tabs'));

            $this->renderLayout();
        } else {
            Mage::getSingleton('adminhtml/session')->addError(Mage::helper('costpriceplus')->__('Banner does not exist'));
            $this->_redirect('*/*/');
        }
    }
    
    public function saveAction() {
        $image = false;
        if ($data = $this->getRequest()->getPost()) {

            $banner_id = $this->getRequest()->getParam('id');
            $model = Mage::getModel('costpriceplus/banner');
            $model->setData($data)->setId($banner_id);
            $upload = $this->imageSave();
            try {
                if ($banner_id) {
                    $image = $this->getRequest()->getParam('image');
                    if (is_array($image)) {
                        if(isset($image['delete']) || $upload) {
                            //delete old pic file
                            $banner = Mage::getModel('costpriceplus/banner')->load($banner_id);
                            $file = $this->getImagePath(). $banner->getImage();
                            if (is_file($file)){
                                unlink($file);
                                $image = '';
                            }
                        }else {
                            $image = $image['value'];
                        }
                    }
                }
                
                if ($upload) {
                    $image = $upload;
                }
                
                if ($this->getRequest()->getParam('start_at') == NULL) {
                    $model->setStart_at(now());
                }
                
                if ($this->getRequest()->getParam('end_at') == NULL) {
                    $model->setEnd_at(NULL);
                } else if (strtotime($model->getEnd_at()) < strtotime($model->getStart_at())){
                    Mage::getSingleton('adminhtml/session')->addError(Mage::helper('costpriceplus')->__('The End Time < Start Time'));
                }
                if ($image){
                    $model->setImage($image);
                }
                $banner_id = $model->save()->getId();
                
                $cats = $this->getRequest()->getParam('cats',array());
                $db = Mage::getSingleton('core/resource')->getConnection('core_write');
                $db->query(" DELETE FROM costpriceplus_category WHERE banner_id = {$banner_id}");
                
                foreach ($cats as $catid) {
                    $catid = (int)$catid;
                    $db->query(" INSERT INTO costpriceplus_category (banner_id, category_id) VALUES ({$banner_id},{$catid})");
                }
                
                if ($this->getRequest()->getParam('status') == 0){
                    Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('costpriceplus')->__('Banner was successfully saved but it status is off!'));
                } else {
                    Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('costpriceplus')->__('Banner was successfully saved'));
                }
                Mage::getSingleton('adminhtml/session')->setFormData(false);

                if ($this->getRequest()->getParam('back')) {
                    $this->_redirect('*/*/edit', array('id' => $model->getId()));
                    return;
                }
                $this->_redirect('*/*/');
                return;
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                Mage::getSingleton('adminhtml/session')->setFormData($data);
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                return;
            }
        }
        Mage::getSingleton('adminhtml/session')->addError(Mage::helper('costpriceplus')->__('Unable to find post to save'));
        $this->_redirect('*/*/');
    }
    
    public function deleteAction() {

        if( $this->getRequest()->getParam('id') > 0 ) {
            $banner_id = $this->getRequest()->getParam('id');
            try {
                
                $banner = Mage::getSingleton('costpriceplus/banner')->load($this->getRequest()->getParam('id'));
                $file = $this->getImagePath(). $banner->getImage();
                if (is_file($file)){
                    unlink($file);
                }
                $banner->delete();
                
                $db = Mage::getSingleton('core/resource')->getConnection('core_write');
                $db->query(" DELETE FROM costpriceplus_category WHERE banner_id = {$banner_id}");
                
                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Bammer was successfully deleted'));
                $this->_redirect('*/*/');
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
            }
        }
        $this->_redirect('*/*/');
    }
    
    
    public function gridAction() {
        //$this->loadLayout();
        //$this->renderLayout();
        $this->getResponse()->setBody($this->getLayout()->createBlock('costpriceplus/grid')->toHtml());
    }

    public function massDeleteAction() {
        
        $bannerIds = $this->getRequest()->getParam('banner');
        if (!is_array($bannerIds)) {
            $this->_getSession()->addError($this->__('Please select banner(s).'));
        } else {
            
            try {
                foreach ($bannerIds as $bannerId) {
                    $banner = Mage::getSingleton('costpriceplus/banner')->load($bannerId);
                    $file = $this->getImagePath(). $banner->getImage();
                    if (is_file($file)){
                        unlink($file);
                    }
                    Mage::dispatchEvent('costpriceplus_controller_banner_delete', array('banner' => $banner));
                    $banner->delete();
                }
                
                $ids = implode(',', $bannerIds);
                $db = Mage::getSingleton('core/resource')->getConnection('core_write');
                $db->query(" DELETE FROM costpriceplus_category WHERE banner_id IN ({$ids})");
                
                $this->_getSession()->addSuccess(
                    $this->__('Total of %d record(s) have been deleted.', count($bannerIds))
                );
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                //$this->_getSession()->addError($e->getMessage());
            }
        }
        $this->_redirect('*/*/index');
    }

    public function massStatusAction() {
        $bannerIds = (array)$this->getRequest()->getParam('banner');
        $storeId    = (int)$this->getRequest()->getParam('store', 0);
        $status     = (int)$this->getRequest()->getParam('status');

        try {
            //$this->_validateMassStatus($bannerIds, $status);
            Mage::getSingleton('costpriceplus/action')
                ->updateAttributes($bannerIds, array('status' => $status), $storeId);

            $this->_getSession()->addSuccess(
                $this->__('Total of %d record(s) have been updated.', count($bannerIds))
            );
        }
        catch (Mage_Core_Model_Exception $e) {
            $this->_getSession()->addError($e->getMessage());
        }
        catch (Mage_Core_Exception $e) {
            $this->_getSession()->addError($e->getMessage());
        }
        catch (Exception $e) {
            $this->_getSession()->addException($e, $this->__('An error occurred while updating the banner(s) status.'));
        }
        $this->_redirect('*/*/', array('store'=> $storeId));
    }
    
    public function _validateMassStatus(array $bannerIds, $status) {
        //not need validate
    }
    
    public function imageSave() {
        
        if (isset($_FILES['image']['tmp_name']['1'])) {
            $path = $this->getImagePath(). 'banner' . DS ;
            $file = array();
            $file['tmp_name'] = $_FILES['image']['tmp_name'];
            $file['name'] = $_FILES['image']['name'];
            
            try{
                $uploader = new Varien_File_Uploader($file);
                $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
                $uploader->setAllowRenameFiles(true);
                $result = $uploader->save($path);
                return 'banner/'.$result['file'];
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }
    
    public function getImagePath() {
        return Mage::getBaseDir('media') . DS;
    }
    

}
